'use strict';

const Service = require('egg').Service;

class BaseService extends Service {
  // 查询数据
  async _findAll(modelName, config) {
    const { ctx } = this;
    const page = Number(config.page || 1);
    const pageSize = Number(config.pageSize || 10);
    try {
      const option = {
        where: config.where || {},
        attributes: config.attributes || null,
        order: config.order,
        limit: pageSize,
        offset: (page - 1) * pageSize,
      };
      const { count, rows } = await ctx.model[modelName].findAndCountAll(option);
      return { count, rows };
    } catch (error) {
      console.log(error);
      this.ctx.logger(error);
      ctx.throw(500, '服务器错误');
    }
  }

  // 根据ID查询数据
  async _findById(modelName, id) {
    const { ctx } = this;
    try {
      return await ctx.model[modelName].findByPk(id);
    } catch (error) {
      ctx.throw(500, '服务器错误');
    }
  }

  // 新增数据
  async _add(modelName, json) {
    const { ctx } = this;
    try {
      await ctx.model[modelName].create(json);
      return '新增成功';
    } catch (error) {
      console.log(error);
      ctx.throw(500, '服务器错误');
    }
  }

  // 编辑数据
  async _edit(modelName, json) {
    const { ctx } = this;
    try {
      const result = await ctx.model[modelName].findByPk(json.id);
      if (!result) return false;
      await result.update({ ...json });
      return '编辑成功';
    } catch (error) {
      console.log(error);
      ctx.throw(500, '服务器错误');
    }
  }

  // 删除数据
  async _delete(modelName, key) {
    const { ctx } = this;
    try {
      const result = await ctx.model[modelName].findByPk(key);
      console.log('result-----', result);
      if (!result) return false;
      await result.destroy();
      return '删除成功';
    } catch (error) {
      console.log(error);
      ctx.throw(500, '服务器错误');
    }
  }
}

module.exports = BaseService;
